#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
模块名称: document_model.py
完整存储路径: backend/models/document.py
功能说明:
    文档管理数据模型，支持隐私政策、用户协议、公告等各类文档的版本管理
    
数据表结构:
    - 文档基本信息（标题、类型、内容）
    - 版本管理（版本号、发布状态、生效时间）
    - 审核流程（创建者、审核者、审核状态）
    - 用户确认记录（用户ID、确认时间、版本号）
"""

from backend.infrastructure.database import db
from datetime import datetime
import enum

class DocumentType(enum.Enum):
    """文档类型枚举"""
    PRIVACY_POLICY = "privacy_policy"      # 隐私政策
    USER_AGREEMENT = "user_agreement"      # 用户协议
    ANNOUNCEMENT = "announcement"          # 公告通知
    HELP_DOC = "help_doc"                 # 帮助文档
    FAQ = "faq"                           # 常见问题

class DocumentStatus(enum.Enum):
    """文档状态枚举"""
    DRAFT = "draft"                       # 草稿
    PENDING_REVIEW = "pending_review"     # 待审核
    APPROVED = "approved"                 # 已审核
    PUBLISHED = "published"               # 已发布
    ARCHIVED = "archived"                 # 已归档

class Document(db.Model):
    """文档主表"""
    __tablename__ = 'documents'
    
    id = db.Column(db.Integer, primary_key=True, autoincrement=True, comment='文档ID')
    title = db.Column(db.String(200), nullable=False, comment='文档标题')
    document_type = db.Column(db.Enum(DocumentType), nullable=False, comment='文档类型')
    content = db.Column(db.Text, nullable=False, comment='文档内容')
    version = db.Column(db.String(20), nullable=False, default='1.0', comment='版本号')
    status = db.Column(db.Enum(DocumentStatus), nullable=False, default=DocumentStatus.DRAFT, comment='文档状态')
    
    # 生效和失效时间
    effective_date = db.Column(db.DateTime, comment='生效时间')
    expiry_date = db.Column(db.DateTime, comment='失效时间')
    
    # 创建和审核信息
    created_by = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, comment='创建者ID')
    reviewed_by = db.Column(db.Integer, db.ForeignKey('users.id'), comment='审核者ID')
    
    # 时间戳
    created_at = db.Column(db.DateTime, default=datetime.utcnow, comment='创建时间')
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, comment='更新时间')
    published_at = db.Column(db.DateTime, comment='发布时间')
    
    # 是否强制阅读（用于隐私政策和用户协议）
    is_mandatory = db.Column(db.Boolean, default=False, comment='是否强制阅读')
    
    # 关联关系
    creator = db.relationship('User', foreign_keys=[created_by], backref='created_documents')
    reviewer = db.relationship('User', foreign_keys=[reviewed_by], backref='reviewed_documents')
    
    def to_dict(self):
        """转换为字典格式"""
        return {
            'id': self.id,
            'title': self.title,
            'document_type': self.document_type.value if self.document_type else None,
            'content': self.content,
            'version': self.version,
            'status': self.status.value if self.status else None,
            'effective_date': self.effective_date.isoformat() if self.effective_date else None,
            'expiry_date': self.expiry_date.isoformat() if self.expiry_date else None,
            'created_by': self.created_by,
            'reviewed_by': self.reviewed_by,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None,
            'published_at': self.published_at.isoformat() if self.published_at else None,
            'is_mandatory': self.is_mandatory,
            'creator_name': self.creator.name if self.creator else None,
            'reviewer_name': self.reviewer.name if self.reviewer else None
        }

class UserDocumentAgreement(db.Model):
    """用户文档确认记录表"""
    __tablename__ = 'user_document_agreements'
    
    id = db.Column(db.Integer, primary_key=True, autoincrement=True, comment='记录ID')
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, comment='用户ID')
    document_id = db.Column(db.Integer, db.ForeignKey('documents.id'), nullable=False, comment='文档ID')
    document_version = db.Column(db.String(20), nullable=False, comment='确认的文档版本')
    agreed_at = db.Column(db.DateTime, default=datetime.utcnow, comment='确认时间')
    ip_address = db.Column(db.String(45), comment='确认时的IP地址')
    user_agent = db.Column(db.String(500), comment='用户代理信息')
    
    # 关联关系
    user = db.relationship('User', backref='document_agreements')
    document = db.relationship('Document', backref='user_agreements')
    
    # 复合唯一索引：一个用户对同一个文档的同一版本只能确认一次
    __table_args__ = (
        db.UniqueConstraint('user_id', 'document_id', 'document_version', name='uk_user_document_version'),
        db.Index('idx_user_document', 'user_id', 'document_id'),
        db.Index('idx_agreed_at', 'agreed_at'),
    )
    
    def to_dict(self):
        """转换为字典格式"""
        return {
            'id': self.id,
            'user_id': self.user_id,
            'document_id': self.document_id,
            'document_version': self.document_version,
            'agreed_at': self.agreed_at.isoformat() if self.agreed_at else None,
            'ip_address': self.ip_address,
            'user_agent': self.user_agent,
            'user_name': self.user.name if self.user else None,
            'document_title': self.document.title if self.document else None
        }

class UserPrivacySetting(db.Model):
    """用户隐私设置表"""
    __tablename__ = 'user_privacy_settings'
    
    id = db.Column(db.Integer, primary_key=True, autoincrement=True, comment='设置ID')
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, unique=True, comment='用户ID')
    
    # 数据收集设置
    data_collection = db.Column(db.Boolean, default=True, comment='基础数据收集')
    personalized_recommend = db.Column(db.Boolean, default=True, comment='个性化推荐')
    behavior_analysis = db.Column(db.Boolean, default=False, comment='行为分析')
    location_services = db.Column(db.Boolean, default=False, comment='位置服务')
    
    # 数据分享设置
    third_party_share = db.Column(db.Boolean, default=False, comment='第三方分享')
    marketing_messages = db.Column(db.Boolean, default=True, comment='营销信息')
    
    # 数据保留设置
    data_retention = db.Column(db.String(20), default='2years', comment='数据保留期限')
    
    # 时间戳
    created_at = db.Column(db.DateTime, default=datetime.utcnow, comment='创建时间')
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, comment='更新时间')
    
    # 关联关系
    user = db.relationship('User', backref=db.backref('privacy_setting', uselist=False))
    
    def to_dict(self):
        """转换为字典格式"""
        return {
            'id': self.id,
            'user_id': self.user_id,
            'data_collection': self.data_collection,
            'personalized_recommend': self.personalized_recommend,
            'behavior_analysis': self.behavior_analysis,
            'location_services': self.location_services,
            'third_party_share': self.third_party_share,
            'marketing_messages': self.marketing_messages,
            'data_retention': self.data_retention,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }
